import { Configuration, App, MidwayDecoratorService, Inject } from "@midwayjs/core";
import * as koa from "@midwayjs/koa";
import * as validate from "@midwayjs/validate";
import * as info from "@midwayjs/info";
import * as swagger from "@midwayjs/swagger"
import * as socketio from "@midwayjs/socketio";
import * as bull from "@midwayjs/bull"
// import * as redis from "@midwayjs/redis"
import { join } from "path";
import { ErrorFilter } from "@/filter/index";
import {
  ReportMiddleware,
  RateLimitMiddleware,
  HaspermiMiddleware
  // ForbidioMiddleware
} from "@/middleware/index";
import { HASPERMISSION_KEY, LOGGING_KEY } from "./decorator";

@Configuration({
  imports: [
    koa,
    validate,
    // redis,
    socketio,
    {
      component: info,
      enabledEnvironment: ["local"],
    },
    bull,
    swagger
  ],
  importConfigs: [join(__dirname, "./config")],
})
export class MainConfiguration {
  @App("koa")
  app: koa.Application;

  @Inject()
  decoratorService: MidwayDecoratorService;

  async onReady() {
    // add middleware

    this.app.useMiddleware([

      HaspermiMiddleware,
      ReportMiddleware,
      RateLimitMiddleware,
      // ForbidioMiddleware
    ]);
    // add filter
    this.app.useFilter([ErrorFilter]);

    this.decoratorService.registerMethodHandler(HASPERMISSION_KEY, (options) => {
      return {
        around: async (joinPoint) => {
          const permission = options.metadata.str || null;
          console.log(permission);

          const result = await joinPoint.proceed(...joinPoint.args);
          return result
        },
      }
    })

    this.decoratorService.registerMethodHandler(LOGGING_KEY, (options) => {
      return {
        around: async (joinPoint) => {

          const opts = options.metadata || null;
          let name = opts.fileName.concat("\\" + options.target.name).concat("\\" + joinPoint.methodName + "()").split(process.env.CHILD_CWD)[1]?.replace(".js", "")
          let methodName = name?.substring(1, name.length).split("\\").join(".");
          console.log(methodName);
          // console.dir(options);
          // console.dir(joinPoint.args[0].req._parsedUrl);
          // console.dir(joinPoint.args[0].params);
          console.dir(joinPoint.args[0].originalUrl);
          

          const result = await joinPoint.proceed(...joinPoint.args);
          return result
        },
      }
    })
  }
}
